<template>
  <div class="question-header">
    <h3>题目 {{ questionIndex + 1 }}</h3>
    <div class="header-actions">
      <el-button v-if="questionIndex === 0" link type="primary" @click="$emit('add-question')">
        <el-icon><Plus /></el-icon>新增题目
      </el-button>
      <el-button link type="danger" @click="$emit('remove-question')"> 删除此题 </el-button>
    </div>
  </div>

  <el-form-item
    :error="errors.title"
    :validate-status="errors.title ? 'error' : ''"
    class="required-label"
    label="题目名称"
    prop="title"
  >
    <el-input
      :model-value="shortAnswerForms[questionIndex].title"
      :rows="2"
      placeholder="请输入题目名称"
      type="textarea"
      @update:model-value="(val) => handleUpdateForm('title', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.answer"
    :validate-status="errors.answer ? 'error' : ''"
    class="required-label"
    label="题目答案"
    prop="answer"
  >
    <el-input
      :model-value="shortAnswerForms[questionIndex].answer"
      :rows="4"
      placeholder="请输入题目答案"
      type="textarea"
      @update:model-value="(val) => handleUpdateForm('answer', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.keywords"
    :validate-status="errors.keywords ? 'error' : ''"
    class="required-label"
    label="答案关键字"
  >
    <div class="keywords-container">
      <div class="keywords-row">
        <div class="tags-wrapper">
          <el-tag
            v-for="(keyword, index) in shortAnswerForms[questionIndex].keywords"
            :key="index"
            :disable-transitions="false"
            class="keyword-tag"
            closable
            @close="handleClose(index)"
          >
            {{ keyword }}
          </el-tag>

          <div v-if="shortAnswerForms[questionIndex].keywords.length < 6" class="input-new-tag">
            <el-input
              v-if="inputVisible"
              ref="inputRef"
              v-model="inputValue"
              :validate-event="false"
              class="tag-input"
              size="small"
              @blur="handleInputConfirm"
              @keydown.enter.prevent="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              <el-icon><Plus /></el-icon>添加关键字
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </el-form-item>

  <el-form-item label="答案解析" prop="analysis">
    <el-input
      :model-value="shortAnswerForms[questionIndex].analysis"
      :rows="3"
      placeholder="请输入答案解析"
      type="textarea"
      @update:model-value="(val) => updateShortAnswerForm(questionIndex, 'analysis', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.difficulty"
    :validate-status="errors.difficulty ? 'error' : ''"
    class="required-label"
    label="难度系数"
    prop="difficulty"
  >
    <el-radio-group
      :model-value="shortAnswerForms[questionIndex].difficulty"
      @update:model-value="(val) => handleUpdateForm('difficulty', val)"
    >
      <el-radio :value="1">简单</el-radio>
      <el-radio :value="2">中等</el-radio>
      <el-radio :value="3">困难</el-radio>
    </el-radio-group>
  </el-form-item>

  <!-- 添加题目分类选择器 -->
  <el-form-item label="题目分类" prop="classId">
    <class-select
      v-model="shortAnswerForms[questionIndex].classId"
      :type="2"
      placeholder="请选择题目分类(选填)"
      @change="(val) => handleUpdateForm('classId', val)"
    />
  </el-form-item>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { nextTick, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useQuestionStore } from '@/store/modules/material/question'
import ClassSelect from '../../compont/ClassSelect.vue'

const props = defineProps<{
  questionIndex: number
  tabName?: string
}>()

const questionStore = useQuestionStore()
const { shortAnswerForms } = storeToRefs(questionStore)
const { updateShortAnswerForm, addKeyword, removeKeyword, updateKeyword } = questionStore

const errors = ref<Record<string, string>>({})

const inputRef = ref<HTMLInputElement>()
const inputVisible = ref(false)
const inputValue = ref('')

// 显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.input?.focus()
  })
}

// 添加实时校验方法
const validateField = (field: string) => {
  const form = shortAnswerForms.value[props.questionIndex]
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【简答题】-第${questionNumber}题：`

  errors.value = { ...errors.value }
  delete errors.value[field]

  switch (field) {
    case 'title':
      if (!form.title?.trim()) {
        errors.value.title = '请输入题目标题'
      }
      break
    case 'answer':
      if (!form.answer?.trim()) {
        errors.value.answer = '请输入题目答案'
      }
      break
    case 'keywords':
      if (form.keywords.length === 0) {
        errors.value.keywords = '请至少添加一个关键字'
      } else {
        const emptyKeywordIndex = form.keywords.findIndex((k) => !k.trim())
        if (emptyKeywordIndex !== -1) {
          errors.value.keywords = '关键字不能为空'
        }
      }
      break
    case 'difficulty':
      if (!form.difficulty) {
        errors.value.difficulty = '请选择难度系数'
      }
      break
  }
}

// 修改更新表单的方法，添加实时校验
const handleUpdateForm = (field: string, value: any) => {
  updateShortAnswerForm(props.questionIndex, field, value)
  validateField(field)
}

// 修改处理输入确认的方法，添加实时校验
const handleInputConfirm = () => {
  if (inputValue.value.trim()) {
    const keywords = shortAnswerForms.value[props.questionIndex].keywords
    if (keywords.length < 6 && !keywords.includes(inputValue.value.trim())) {
      shortAnswerForms.value[props.questionIndex].keywords.push(inputValue.value.trim())
      validateField('keywords')
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 修改处理标签关闭的方法，添加实时校验
const handleClose = (index: number) => {
  removeKeyword(props.questionIndex, index)
  validateField('keywords')
}

// 校验方法
const validate = () => {
  const errorMessages: string[] = []
  errors.value = {}
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【简答题】-第${questionNumber}题：`

  if (!shortAnswerForms.value[props.questionIndex].title?.trim()) {
    errorMessages.push(`${tabPrefix}请输入题目标题`)
    errors.value.title = '请输入题目标题'
  }

  if (!shortAnswerForms.value[props.questionIndex].answer?.trim()) {
    errorMessages.push(`${tabPrefix}请输入题目答案`)
    errors.value.answer = '请输入题目答案'
  }

  // 校验关键字
  const keywords = shortAnswerForms.value[props.questionIndex].keywords
  if (keywords.length === 0) {
    errorMessages.push(`${tabPrefix}请至少添加一个关键字`)
    errors.value.keywords = '请至少添加一个关键字'
  } else {
    const emptyKeywordIndex = keywords.findIndex((k) => !k.trim())
    if (emptyKeywordIndex !== -1) {
      errorMessages.push(`${tabPrefix}关键字不能为空`)
      errors.value.keywords = '关键字不能为空'
    }
  }

  if (!shortAnswerForms.value[props.questionIndex].difficulty) {
    errorMessages.push(`${tabPrefix}请选择难度系数`)
    errors.value.difficulty = '请选择难度系数'
  }

  return {
    valid: errorMessages.length === 0,
    errors: errorMessages
  }
}

const getFormData = () => {
  return {
    ...shortAnswerForms.value[props.questionIndex]
  }
}

defineExpose({
  validate,
  getFormData
})

defineEmits(['add-question', 'remove-question'])
</script>

<style lang="scss" scoped>
.keywords-container {
  width: 100%;

  .keywords-row {
    display: flex;
    align-items: center;
    gap: 8px;
    min-height: 32px;
  }

  .tags-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }

  .keyword-tag {
    margin: 0;
  }

  .input-new-tag {
    display: inline-flex;
    align-items: center;
  }

  .tag-input {
    width: 90px;
    margin-left: 0;
  }

  .button-new-tag {
    height: 32px;
    padding: 0 10px;
  }
}

.error-message {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-top: 4px;
}

.required-label {
  :deep(.el-form-item__label) {
    &::before {
      content: '*';
      color: var(--el-color-danger);
      margin-right: 4px;
    }
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}
</style>
